<?php
namespace app\api\controller;

use think\Db;
use think\Config;

class Ucenter
{
    public function wxLogin()
    {
        $APPID = Config::get('wxxcx.appid');//"wxbeca3a40fc7753b4";
        $SECRET = Config::get('wxxcx.secret');//"cac903c99dabd80c30304c0dbc94d3f7";
        $code = input("code");
        $nickname = input("nickname");

        $URL = "https://api.weixin.qq.com/sns/jscode2session";
        $data = ["appid" =>$APPID,"secret" => $SECRET ,"js_code" =>$code ,"grant_type" => "authorization_code"];
        $result = json_decode(httpRequest($URL, $data),true);
        
        $wx_openid = $result['openid'];
        $userInfo = Db::name("user")->where("wx_openid",$wx_openid)->find();
        $sessionKey = md5(rand(10000,99999).time());
        if($userInfo){
            if ( !$userInfo['nickname'] ){
                Db::name("user")->where("wx_openid",$wx_openid)->update( array('nickname'=>$nickname));
            }
            cache($sessionKey,  $wx_openid);
            to_json(1,'', ["code" => 0 ,"sessionKey" =>$sessionKey, "uid" => $userInfo['id'], "roleid" => $userInfo['roleid'] ]);
        }else{
            $username = "wx" .rand(1000000,9999999);
            $userInfo = Db::name("user")->insert(["wx_openid" => $wx_openid,"username" => $username,"nickname" => $nickname,"roleid"=>1]);
            if($userInfo){
                cache($sessionKey,  $wx_openid);
                to_json(1,'', ["code" => 0 ,"sessionKey" =>$sessionKey, "uid" => $userInfo['id'], "roleid" => $userInfo['roleid'] ]);
            }
        }
    }
}